package com.wlz.embedded;

import io.netty.buffer.*;
import io.netty.channel.embedded.EmbeddedChannel;
import org.junit.Test;

import java.nio.charset.Charset;

/**
 * 本地测试模式  用来测试handler的执行  就不需要完整的实现客户端或者服务端
 */
public class BufferEmbedded {
    /**
     * buffer 测试
     */
    @Test
    public void test1() {
        EmbeddedChannel embeddedChannel = new EmbeddedChannel(new NettyClientHandler());

        ByteBuf buf = PooledByteBufAllocator.DEFAULT.buffer();
        buf.setBoolean(0,true);
        buf.setCharSequence(1,"hello world", Charset.defaultCharset());

        embeddedChannel.writeInbound(buf);
    }

    /**
     * 非池化直接缓冲区和堆缓冲区申请性能的测试
     * 每种申请100000次  统计耗时
     */
    @Test
    public void test2() {
        long start = System.currentTimeMillis();
        int count = 100000;
        for (int i = 0; i < count; i++) {
            ByteBuf buf = Unpooled.directBuffer(1024);
        }
        long end = System.currentTimeMillis();
        System.out.println("直接缓冲区申请耗时：" + (end - start));

        long start1 = System.currentTimeMillis();
        for (int i = 0; i < count; i++) {
            ByteBuf buf = Unpooled.buffer(1024);
        }
        long end2 = System.currentTimeMillis();
        System.out.println("堆缓冲区申请耗时：" + (end2 - start1));
    }

    /**
     * 非池化直接缓冲区和堆缓冲区释放性能的测试
     * 添加100000个直接缓冲区和堆缓冲区，记录释放的时间
     */
    @Test
    public void test3() {
        int count = 100000;
        ByteBuf[] directBufs = new ByteBuf[count];
        for (int i = 0; i < count; i++) {
            ByteBuf buf = Unpooled.directBuffer(1024);
            directBufs[i] = buf;
        }
        //直接缓冲区记录开始
        long start = System.currentTimeMillis();
        for (int i = 0; i < count; i++) {
            directBufs[i].release();
        }
        long end = System.currentTimeMillis();
        System.out.println("直接缓冲区释放耗时：" + (end - start));
        //直接缓冲区记录结束

        ByteBuf[] heapBufs = new ByteBuf[count];
        for (int i = 0; i < count; i++) {
            ByteBuf buf = Unpooled.buffer(1024);
            heapBufs[i] = buf;
        }
        long start1 = System.currentTimeMillis();
        for (int i = 0; i < count; i++) {
            heapBufs[i].release();
        }
        long end1 = System.currentTimeMillis();
        System.out.println("堆缓冲区耗时：" + (end1 - start1));
    }

    /**
     * 非池化直接内存溢出测试
     * 不手动释放，会触发内存溢出
     */
    @Test
    public void test4() {
        ByteBufAllocator alloc= UnpooledByteBufAllocator.DEFAULT;
        for (int i = 0; i < 10000; i++) {
            System.out.println(i);
            ByteBuf buf = alloc.directBuffer(1024 * 1024);
            buf.release();
        }
    }

    /**
     * 堆内存  jvm自行回收
     */
    @Test
    public void test6() {
        ByteBufAllocator alloc= UnpooledByteBufAllocator.DEFAULT;
        for (int i = 0; i < 10000; i++) {
            System.out.println(i);
            ByteBuf buf = alloc.heapBuffer(1024 * 1024);
        }
    }
}
